#include <QApplication>

#include "httpserver.h"
#include "mainwindow.h"

#include "main.h"

#include "collection/collection.h"
#include "configdialog.h"
#include "player.h"
#include <QSettings>
#include <QLabel>

#include "networkconfig.h"

Main::Main()
    : local(false)
{

}

int Main::run(int argc, char**argv)
{
    QApplication a(argc, argv);
    a.setStartDragTime(500);
    a.setStartDragDistance(20);
    a.setOrganizationName("Unix Junkies");
    a.setOrganizationDomain("unix-junkies.org");
    a.setApplicationName("Playur");
    
    if(a.arguments().contains("--local"))
        local = true;
    
    //if(!local)
        Playur::ConfigDialog().exec();
    
    collection.addFolder(QSettings().value("libraryPath").toString());
    collection.scan();
    collection.setNickname(QSettings().value("nickname").toString());
    
    if(local)
        networkConfig = new OfflineNetworkConfig();
    else
        networkConfig = new UPNPNetworkConfig();
    
    mainWindow = new MainWindow();
    mainWindow->show();
    
    connect(networkConfig, SIGNAL(done()), this, SLOT(networkReady()));
    networkConfig->setup();
    
    Playur::Player player;
    player.show();
    
    return a.exec();
}

void Main::networkReady()
{
    server.listen(QHostAddress::Any, networkConfig->port());
    QString hostAddress = networkConfig->address() + ":" +  QString::number(networkConfig->port());
    qDebug() << "Listening on" << hostAddress;
    
    if(!local) {
        buddyList = new Playur::BuddyList(QSettings().value("identifier").toString(), hostAddress);
        connect(buddyList, SIGNAL(buddyConnected(const QString&)), this, SLOT(buddyConnected(const QString&)));
    }
    
    collection.setUrl(QString("http://") + hostAddress);
    server.setCollection(&collection);
    
    if(local)
        mainWindow->fetchCollection("127.0.0.1:3530");
}

void Main::buddyConnected(const QString& name)
{
    mainWindow->fetchCollection(buddyList->get()[name]);
}

int main(int argc, char** argv)
{
    return (new Main())->run(argc, argv);
}
